package tgc.edu.ljc.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import tgc.edu.ljc.custom.CommonService;
import tgc.edu.ljc.entity.SysRole;
import tgc.edu.ljc.entity.SysUser;
import tgc.edu.ljc.repository.SysUserRepository;
import tgc.edu.ljc.security.User2;
@Service
public class SysUserService  extends CommonService<SysUser, Integer> implements UserDetailsService{
	@Autowired
	private SysUserRepository sysUserDAO; 
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user=sysUserDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		List<SysRole> roles=user.getRoles();
		List<GrantedAuthority> authorities=new ArrayList<>();
		for (SysRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
        return new User2(user.getUsername(), user.getPassword(),user.getName(), authorities);
	}


}
